package com.dhl.deliver.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dhl.deliver.dto.DingdanInfo;
import com.dhl.deliver.dto.GoodsDto;
import com.dhl.deliver.dto.OrderDto;
import com.dhl.deliver.entity.Dingdan;
import com.dhl.deliver.entity.Goods;
import com.dhl.deliver.entity.Product;
import com.dhl.deliver.entity.Shop;
import com.dhl.deliver.service.*;
import com.dhl.deliver.utils.GridResultWrapper;
import com.dhl.deliver.utils.Result;
import com.dhl.deliver.utils.ResultUtil;
import com.dhl.deliver.utils.TimeUtil;
import com.dhl.deliver.vo.GoodsVo;
import com.dhl.deliver.vo.OrderVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dhl
 * @since 2020-08-09
 */
@RestController
@RequestMapping("/order")
public class DingdanController {

//    public static final int ORDER_STATE_WAIT=0;     //等待发货
//    public static final int ORDER_STATE_RUNNING=1;  //派送中
//    public static final int ORDER_STATE_FINISHED=2; //已完成

    @Resource
    IUserService userService;

    @Resource
    IDingdanService orderService;

    @Resource
    IGoodsService goodsService;

    @Resource
    IProductService productService;

    @Resource
    IShopService shopService;

//    @ApiOperation("新增订单")
//    @PostMapping("/addOrder")
//    @Transactional(propagation=Propagation.REQUIRED)
//    public Result addOrder(HttpServletRequest request, @RequestBody List<GoodsDto> goodsDtos){
//        Order order=new Order();
//        order.setUserId(userService.getCurrentUserId(request));
//        order.setStatus(ORDER_STATE_WAIT);
//        orderService.save(order);
//        List<Goods> goodsList =new LinkedList<>();
//        float summary =0;
//        for (GoodsDto dto:
//                goodsDtos) {
//            Goods goods = new Goods();
//            BeanUtils.copyProperties(dto,goods);
//            goods.setOrderId(order.getId());
//            goodsList.add(goods);
//            summary+=dto.getPrice();
//        }
//        order.setSummary(summary);
//        order.setCreateTime(LocalDateTime.now());
//        orderService.updateById(order);
//        goodsService.saveBatch(goodsList);
//        return ResultUtil.success();
//    }

    @ApiOperation("新增订单(json格式)")
    @PostMapping("/addOrderByJson")
    @Transactional(propagation= Propagation.REQUIRED)
    public Result addOrderByJson(HttpServletRequest request, @RequestBody OrderDto orderdto){
        Dingdan dingdan =new Dingdan();
        dingdan.setUserId(userService.getCurrentUserId(request));
        orderService.save(dingdan);
        List<Goods> goodsList=new LinkedList<>();
        float summary=0;
        for (GoodsDto dto:orderdto.getProducts()){
            Goods goods = new Goods();
            Product product=productService.getById(dto.getId());
            Shop shop=shopService.getById(product.getShopId());
            goods.setProductName(product.getName());
            goods.setShopName(shop.getName());
            goods.setProductId(dto.getId());
            goods.setNum(dto.getCount());
            goods.setPrice(dto.getPrice());
            goods.setOrderId(dingdan.getId());
            goodsService.save(goods);
            goodsList.add(goods);
            summary+=dto.getPrice()*dto.getCount();
        }
        dingdan.setSummary(summary);
        if(orderdto.isReserve()) {
            dingdan.setStatus(1);
            dingdan.setPlaneTime(new TimeUtil().dataTransfer(orderdto.getDate()));
        }
        else
            dingdan.setStatus(0);
        dingdan.setAddressId(orderdto.getAddress_id());
        dingdan.setRemark(orderdto.getRemark());

        orderService.updateById(dingdan);
        return ResultUtil.success(dingdan);
    }

    @ApiOperation("获取当前用户的订单")
    @GetMapping("/getOrder")
    public Result getOrder(HttpServletRequest request){    //普通获取数据
        String user_id=userService.getCurrentUserId(request);
        Wrapper<Dingdan> wrapper=new QueryWrapper<Dingdan>().eq("user_id",user_id);
        List<Dingdan> list=orderService.list(wrapper);
        List<DingdanInfo> list1=new ArrayList<>();
        for(Dingdan order:list){
            Wrapper<Goods> goodsWrapper=new QueryWrapper<Goods>().eq("order_id",order.getId());
            List<Goods> goodsList=goodsService.list(goodsWrapper);
            DingdanInfo dingdanInfo=new DingdanInfo();
            dingdanInfo.setDingdan(order);
            dingdanInfo.setGoodsList(goodsList);
            list1.add(dingdanInfo);
        }
        return ResultUtil.success(list1);
    }
    @ApiOperation("获取当前用户的订单，分页")
    @GetMapping("/getOrderByPage")
    public Result getOrderByPage(int pageNum,int size){  //分页获取数据
        IPage<Dingdan> page=new Page<Dingdan>(pageNum,size);
        IPage<Dingdan> resultPage = orderService.query().orderByDesc("create_time").page(page);
        List<Dingdan> Dingdans = resultPage.getRecords();
        List<OrderVo> orderVoList =new LinkedList<>();
        for (Dingdan o :
                Dingdans) {
            List<Goods> goodsList = goodsService.query().eq("order_id", o.getId()).list();
            List<GoodsVo> goodsVoList = new LinkedList<>();
            for (Goods g :
                    goodsList) {
                GoodsVo goodsVo = new GoodsVo();
                BeanUtils.copyProperties(g,goodsVo);
                Product product = productService.getById(g.getProductId());
                goodsVo.setProductName(product.getName());
                goodsVoList.add(goodsVo);
            }
            OrderVo orderVo =new OrderVo();
            BeanUtils.copyProperties(o,orderVo);
            orderVo.setGoodsVoList(goodsVoList);
            orderVoList.add(orderVo);
        }
        GridResultWrapper resultWrapper = new GridResultWrapper(resultPage.getTotal(), Dingdans);
        Result result = ResultUtil.success(resultWrapper);
        return result;
    }

//    @ApiOperation("结算订单,返回订单金额，修改订单状态")
//    @PostMapping("/settle")
//    public  Result Settle(String id){
//        Order order=orderService.getById(id);
//        if(order==null)
//            return ResultUtil.error(500,"未查到该订单");
//        order.setStatus(1);
//        return ResultUtil.success(order.getSummary());
//    }
//
//    @ApiOperation("完成订单，修改订单状态")
//    @PostMapping("/finish")
//    public Result finish(String id){
//        Order order=orderService.getById(id);
//        if(order==null)
//            return ResultUtil.error(500,"未查到该订单");
//        order.setStatus(2);
//        order.setFinishTime(LocalDateTime.now());
//        return ResultUtil.success();
//    }

    @ApiOperation("设置送餐时间")
    @PostMapping("/setPostTime")
    public Result setPostTime(String id, Date time){
        LocalDateTime postTime;
        postTime=new TimeUtil().dataTransfer(time);
        Dingdan dingdan = orderService.getById(id);
        if(dingdan ==null)
            return ResultUtil.error(500,"订单错误");
        dingdan.setPlaneTime(postTime);
        return ResultUtil.success();
    }


}